<!--保洁员考核模板-->
<template>
  <div class="newCheckContainer">
    <!--头部bar开始-->
    <CommonBar :options="options"></CommonBar>
    <!--头部bar结束-->
    <!--图片预览开始-->
    <div class="preViewDiv" v-if="preViewshow">
      <div class="preViewDivTop">
        <div class="custom-indicator" slot="indicator">{{ current + 1 }}/{{photoimg.length}}</div>
        <van-icon name="clear" class="closeable" @click="preViewshow=!preViewshow" />
      </div>
      <van-swipe class="my-swipe" @change="onChange" :show-indicators="false">
        <van-swipe-item v-bind:key="index" v-for="(item,index) in photoimg">
          <van-icon name="delete" class="deleteable" @click="del(current)" />
          <van-image :src="item.url" class="bannerimg" fit="cover" height="100%" width="100%" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <!--图片预览结束-->
    <div class="divheight"></div>
    <!--考核员指标开始-->
    <div class="zhibiao">
      <p :class="ellipsis?'ellipsis':'unellipsis'" class="zhibiaoitem descontent">
        <span v-for="item in TemplateKpiTop" :key="item.id">
          {{item.remark}}
          <br />
        </span>
      </p>
      <p class="showdesc" @click="ela">
        {{ellipsis?'展开':'收起'}}
        <van-icon :name="ellipsis?'arrow-down':'arrow-up'" class="arrowicon" />
      </p>
    </div>
    <!--考核员指标结束-->
    <div class="divheight"></div>

    <!--打分开始-->
    <div class="scorecontent">
      <div class="countScoreDiv">
        <div class="countScoreTop">
          <p class="name">
            保洁员:
            <span>{{clearnName}}</span>
          </p>
          <p>{{signdate}}</p>
        </div>
      </div>
      <div class="countScoreHeader">
        <van-row>
          <van-col :span="12">考核项名称</van-col>
          <van-col :span="6" class="textcenter">得分</van-col>
          <van-col :span="3" class="textcenter">拍照</van-col>
          <van-col :span="3" class="textright">查看</van-col>
        </van-row>
      </div>
      <div>
        <van-row v-for="(item ,$index) in TemplateKpi" :key="$index" class="rowItem">
          <van-col :span="12">{{item.name}}({{item.newscore}}分)</van-col>
          <van-col :span="6">
            <input
              type="number"
              v-model="item.score"
              class="scoreinput"
              @blur="computsocre(item.score,item.newscore)"
            />
          </van-col>
          <van-col :span="3" @click="takephoto($index)" class="textcenter">
            <van-image width="22" height="22" :src="takephoto1" style="vertical-align: middle;" />
          </van-col>
          <van-col :span="3" class="textright" @click="ViewImg($index)">
            <van-image width="22" height="22" :src="item.viewimg" style="vertical-align: middle;" />
          </van-col>
        </van-row>
        <van-action-sheet v-model="takephotoshow" :actions="actions" @select="takephotoSelect" />
      </div>
      <p class="allcount">
        总分:
        <span>{{sumconunt}}</span>
      </p>
      <div class="buttonbot">
        <p class="pass" @click="savedata">保存</p>
        <p class="refuse" @click="submit">提交</p>
      </div>
    </div>
    <!--加载框开始-->
    <van-overlay :show="showloading">
      <div class="wrapper">
        <div class="loadingcont">
          <van-loading size="24px" vertical>{{loaddingText}}</van-loading>
        </div>
      </div>
    </van-overlay>
    <!--加载框结束-->
  </div>
</template>
<script>
import { Dialog } from "vant";
import { ImagePreview } from "vant";
import { compressImage } from "../../common/compressImage";
import CommonBar from "../../common/commonBar";
import { mapState } from "vuex";
export default {
  components: {
    CommonBar
  },
  computed: {
    ...mapState({
      token: state => state.Authorization,
      user_department_type: state => state.userData.department_type, //人员类型
      user_department_id: state => state.userData.department_id, // 人员id
      group_department_id: state => state.userData.group_department_id,
      project_company_id: state => state.userData.project_company_id,
      project_id: state => state.userData.project_id,
      district_id: state => state.userData.district_id
    })
  },
  data() {
    return {
      value1: "",
      pattern: "/d{6}/",
      ellipsis: true,
      takephoto1: require("../../../../static/image/takephoto.png"),
      viewImg1: require("../../../../static/image/viewImg.png"),
      viewImghui: require("../../../../static/image/viewimghui.png"),
      //加载框
      showloading: false,
      loaddingText: "加载中",

      //公共bar
      options: {
        type: "icon",
        centerText: "保洁员指标考核",
        iconNname: "wap-home",
        lefttype: "left"
      },

      TemplateKpi: [], //指标表格信息
      TemplateKpiTop: [], //指标内容
      clearnName: "", //保洁员姓名
      signdate: "", //当前日期
      scoreinput: "",
      photo: [],
      detailresult: [],
      //相机
      actions: [
        { name: "相机", id: "1" },
        { name: "图库", id: "2" },
        { name: "取消", id: "3" }
      ],
      takephotoshow: false,
      currentLng: "",
      currentLat: "",
      currentDateTime: "",
      imgUrl: "",
      countindex: "",
      //查看图片
      showimg: false,
      imgext: "",
      template_id: "",
      is_power: "", //判断是否能提交
      //预览图片带删除
      preViewshow: false,
      current: 0,
      photoimg: [],
      TemplateKpi1: [],
      sumconunt: 0,
      duty_id: "",
      arrchenge: ""
    };
  },
  created() {
    this.duty_id = this.$route.query.id;
    //获取名称
    var params = {
      duty_id: this.duty_id,
      token: this.token
    };
    this.getClearnName(params);
    this.getloadData();
    this.showDate();
  },
  //当拍照改变后photo数组就为空
  watch: {
    countindex(newval, oldval) {
      this.photo = [];
    },
    TemplateKpi: {
      handler: function(newVal, oldval) {
        if (oldval.length <= 0) {
          this.arrchenge = false;
        } else {
          this.arrchenge = true;
        }
        let new_arr = newVal.map(obj => {
          return obj.score;
        });
        var r = new_arr.filter(function(s) {
          return s && s.trim();
        });
        var sum = 0;
        for (let i = 0; i < r.length; i++) {
          sum += parseInt(r[i]);
        }
        this.sumconunt = sum;
      },
      deep: true //深度监听
    }
  },
  destroyed() {
    var that = this;
    document.removeEventListener("backbutton", that.backbutton, false);
  },
  mounted() {
    var that = this;
    document.addEventListener("backbutton", that.backbutton, false);
  },
  methods: {
    backbutton() {
      if (this.arrchenge) {
        Dialog.confirm({
          title: "提示",
          message: "内容未保存，是否返回"
        })
          .then(() => {
            history.back();
          })
          .catch(() => {
            // on cancel
          });
      } else {
        history.back();
      }
    },
    computsocre(score, newscore) {
      console.log(score, newscore);
      if (score > newscore) {
        this.$toast({ message: "考核分数不能大于指标分数" });
      }
    },
    ela() {
      this.ellipsis = !this.ellipsis;
    },
    /**
     * onChange预览照片时的轮播方法
     * del删除预览照片
     */
    onChange(index) {
      this.current = index;
    },

    del(id) {
      Dialog.confirm({
        title: "提示",
        message: "是否删除该照片"
      })
        .then(() => {
          this.photoimg.splice(id, 1);
          this.current = 0;
          if (this.photoimg.length == 0) {
            this.current = -1;
          }
        })
        .catch(() => {
          // on cancel
        });
    },
    //拍照事件
    takephoto(template_id) {
      this.takephotoshow = true;
      this.countindex = template_id;
    },
    //选中图片方式，1是相机，2是图库
    takephotoSelect(item) {
      this.takephotoshow = false;
      if (item.id == 3) {
        this.$toast({ message: "取消上传图片" });
      } else if (item.id == 2) {
        var srcType = Camera.PictureSourceType.PHOTOLIBRARY;
        this.$nextTick(() => {
          this.getLoation();
        });
        this.showTime(); //获取当前时间
        this.cameraTakePicture(srcType); //调用相机
      } else if (item.id == 1) {
        var srcType = Camera.PictureSourceType.CAMERA;
        this.$nextTick(() => {
          this.getLoation();
        });
        this.showTime(); //获取当前时间
        this.cameraTakePicture(srcType); //调用相机
      } else if (
        this.TemplateKpi[this.countindex].photo &&
        this.TemplateKpi[this.countindex].photo.length >= 5
      ) {
        this.$toast({ message: "不能上传超过5张" });
      }
    },
    //拍照

    cameraTakePicture(mySourceType) {
      //把缓存里的takephoto里的丢进onsuces
      let that = this;
      navigator.camera.getPicture(onSuccess, onFail, {
        quality: 50,
        destinationType: Camera.DestinationType.DATA_URL,
        encodingType: Camera.EncodingType.JPEG,
        sourceType: mySourceType
      });

      function onSuccess(imageData) {
        var imageurl = "data:image/jpeg;base64," + imageData;
        var lng = localStorage.getItem("currentLat");
        var lat = localStorage.getItem("currentLng");
        that.showTime(); //获取当前时间
        var ret = {};
        ret.createtime = that.currentDateTime;
        ret.position = { lon: lng, lat: lat };
        //查看大小
        var str = imageData;
        var equalIndex = str.indexOf("=");
        if (str.indexOf("=") > 0) {
          str = str.substring(0, equalIndex);
        }
        var strLen = str.length;
        var fileSize = strLen - (strLen / 8) * 2;
        var size = (fileSize / 1024).toFixed(2);
        if (parseInt(size) > 1024) {
          compressImage(imageurl, {
            width: 200,
            quality: 0.4 // 压缩后图片的宽
            // 压缩后图片的高，宽高若只传一个，则按图片原比例进行压缩
            // 压缩后图片的清晰度，取值0-1，不传默认为0.7，值越小，所绘制出的图像越模糊
          }).then(result => {
            ret.url = result;
            that.photo.push(ret);
            that.TemplateKpi[that.countindex].photo = that.photo;
            if (that.TemplateKpi[that.countindex].photo.length > 0) {
              that.TemplateKpi[that.countindex].viewimg = that.viewImg1;
            }
          });
        } else {
          ret.url = imageurl;
          that.photo.push(ret);
          that.TemplateKpi[that.countindex].photo = that.photo;
          if (that.TemplateKpi[that.countindex].photo.length > 0) {
            that.TemplateKpi[that.countindex].viewimg = that.viewImg1;
          }
        }
      }

      function onFail(message) {
        this.$toast({ message: message });
      }
    },
    //显示图片弹窗
    ViewImg(index) {
      var array = this.TemplateKpi[index].photo;
      if (array === undefined || array.length == 0) {
        this.$toast({ message: "未上传照片" });
      } else {
        this.photoimg = this.TemplateKpi[index].photo;
        console.log("弹出数组", this.photoimg);
        this.preViewshow = true;
        this.current = 0;
      }
    },

    //获取当前经纬度
    getLoation() {
      let _this = this;
      var geolocation = new BMap.Geolocation();
      // 开启SDK辅助定位
      geolocation.enableSDKLocation();
      geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          const myGeo = new BMap.Geocoder();
          myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), data => {
            if (data.addressComponents) {
              var result = data.addressComponents;
              var pathlocation = {
                creditLongitude: r.point.lng, // 经度
                creditLatitude: r.point.lat, // 纬度
                creditProvince: result.province || "", // 省
                creditCity: result.city || "", // 市
                creditArea: result.district || "", // 区
                creditStreet:
                  (result.street || "") + (result.streetNumber || "") // 街道
              };
              _this.currentLng = pathlocation.creditLongitude;
              _this.currentLat = pathlocation.creditLatitude;
              localStorage.setItem("currentLng", _this.currentLng);
              localStorage.setItem("currentLat", _this.currentLat);
            }
          });
        }
      });
    },
    //获取当前时间
    showTime() {
      var d = new Date();
      this.currentDateTime =
        d.getFullYear() +
        "-" +
        (d.getMonth() + 1) +
        "-" +
        d.getDate() +
        " " +
        d.getHours() +
        ":" +
        d.getMinutes() +
        ":" +
        d.getSeconds();
    },
    /**获取保洁员信息 */
    getClearnName(params) {
      this.$http
        .get(`${this.$basePath}?service=App.Cleaner.GetCleaner&api=86`, {
          params: params
        })
        .then(res => {
          this.is_power = res.data.is_power;
          console.log("保洁员信息", this.is_power);
          if (res.ret == 200 && res.data.name) {
            this.clearnName = res.data.name;
            console.log("保洁员信息", res);
          } else {
            this.clearnName = "";
            this.$toast({ message: "该片区未分配保洁员" });
          }
        });
    },
    //指标信息
    getloadData() {
      this.$toast.loading({
        mask: true,
        message: "加载中...",
        duration: 5000
      });
      var params = { token: this.token, template_id: 2 };
      this.$http
        .get(`${this.$basePath}?service=App.TemplateKpi.GetKpiList&api=86`, {
          params: params
        })
        .then(res => {
          if (res.ret == 200) {
            this.$toast.clear();
            console.log("指标信息", res);
            this.TemplateKpiTop = res.data;
            //this.TemplateKpi = res.data;
            var reformattedArray = [];
            res.data.forEach(function(item) {
              reformattedArray.push({
                id: item.id,
                score: item.score,
                name: item.name
              });
            });
            console.log("提前出来的数组", reformattedArray);
            var that = this;
            this.TemplateKpi = reformattedArray.map(function(obj, index) {
              obj.newscore = obj.score; //添加id属性
              obj.viewimg = that.viewImghui;
              return obj; //如果不返回则输出： Array [undefined, undefined, undefined
            });
            console.log("新数组", this.TemplateKpi);

            this.template_id = res.data[0].template_id;
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    /*提交分数事件*/
    postdata(params) {
      this.$http
        .post(
          `${this.$basePath}?service=App.Cleaner.UpdateCheck&api=86`,
          params
        )
        .then(res => {
          if (res.ret == 200) {
            this.$toast({ message: res.msg });
            this.showloading = false;
            console.log("提交分数", res);
            //提交后清空数据
            this.$router.push({
              //核心语句
              path: "/cleanerList" //跳转的路径
            });
          } else {
            this.$toast({ message: res.msg });
            this.showloading = false;
          }
        });
    },
    //数据保存中
    savedata() {
      if (this.is_power) {
        var result = [];
        console.log("添加对象", this.TemplateKpi);
        this.TemplateKpi.forEach(function(item) {
          result.push({
            id: item.id,
            score: item.score,
            photo: item.photo
          });
        });
        //判断有么有空值
        let result1 = result.find(obj => {
          return obj.score == "";
        });
        console.log("是否有空值", result1);
        if (result1 != undefined) {
          this.$toast({ message: "请填写完整分数", duration: 2000 });
        } else if (this.sumconunt > 100) {
          this.$toast({ message: "总分超过100分，请重新打分" });
        } else {
          this.loaddingText = "数据保存中...";
          this.showloading = true;
          console.log("kpi", result);

          var params = {
            token: this.token,
            id: 0,
            group_department_id: this.group_department_id,
            project_company_id: this.project_company_id,
            project_id: this.project_id,
            district_id: this.district_id,
            duty_id: this.duty_id,
            result: JSON.stringify(result),
            statu: 0,
            template_id: this.template_id
          };
          console.log("params", params);
          this.postdata(params);
        }
      } else {
        this.$toast({ message: "暂未授权,不能提交信息" });
      }
    },
    //数据提交
    submit() {
      if (this.is_power) {
        var result = [];
        console.log("添加对象", this.TemplateKpi);
        this.TemplateKpi.forEach(function(item) {
          result.push({
            id: item.id,
            score: item.score,
            photo: item.photo
          });
        });
        //判断有么有空值
        let result1 = result.find(obj => {
          return obj.score == "";
        });
        console.log("是否有空值", result1);
        if (result1 != undefined) {
          this.$toast({ message: "请填写完整分数", duration: 2000 });
        } else if (this.sumconunt > 100) {
          this.$toast({ message: "总分超过100分，请重新打分" });
        } else {
          this.loaddingText = "数据提交中...";
          this.showloading = true;
          console.log("kpi", result);
          var params = {
            token: this.token,
            id: 0,
            group_department_id: this.group_department_id,
            project_company_id: this.project_company_id,
            project_id: this.project_id,
            district_id: this.district_id,
            duty_id: this.duty_id,
            result: JSON.stringify(result),
            statu: 1,
            template_id: this.template_id
          };
          console.log("params", params);
          this.postdata(params);
        }
      } else {
        this.$toast({ message: "暂未授权,不能提交信息" });
      }
    },
    //系统日期
    showDate() {
      var d = new Date();
      let year = d.getFullYear();
      let month = d.getMonth() + 1;
      let day = d.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      this.signdate = year + "-" + month + "-" + day;
    }
  }
};
</script>
<style lang="less" scoped>
@import "../../../assets/css/check";

/* 展开收缩 */
</style>